#!/bin/bash

# 记账本APK构建脚本

echo "📱 开始构建记账本APK..."

# 设置项目根目录和环境变量
PROJECT_ROOT="/home/zhangdaye/node_vue"
export ANDROID_HOME="/home/zhangdaye/Android"
export PATH="$PATH:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools"
export JAVA_HOME="/usr/lib/jvm/java-17-openjdk-amd64"

cd "$PROJECT_ROOT"

echo "🌍 环境变量:"
echo "ANDROID_HOME: $ANDROID_HOME"
echo "JAVA_HOME: $JAVA_HOME"
echo ""

# 检查前端构建文件是否存在
if [ ! -d "frontend/dist" ]; then
    echo "🔨 构建前端项目..."
    cd frontend
    npm run build-only || { echo "❌ 前端构建失败"; exit 1; }
    cd "$PROJECT_ROOT"
fi

# 创建Cordova项目（如果不存在）
if [ ! -d "mobile" ]; then
    echo "📦 创建Cordova项目..."
    cordova create mobile com.accounting.app "记账本" || { echo "❌ Cordova项目创建失败"; exit 1; }
    cd mobile
    cordova platform add android || { echo "❌ 添加Android平台失败"; exit 1; }
    cd "$PROJECT_ROOT"
fi

# 复制构建文件到Cordova项目
echo "📋 复制前端文件..."
rm -rf mobile/www/*
cp -r frontend/dist/* mobile/www/

# 获取本机IP地址
LOCAL_IP=$(hostname -I | awk '{print $1}')
echo "🔧 配置API地址: $LOCAL_IP"

# 修改API基础URL为可访问的IP地址
# 在移动端，需要将API请求指向真实的服务器IP
find mobile/www/assets -name "*.js" -exec sed -i "s|baseURL: '/api'|baseURL: 'http://${LOCAL_IP}:3000/api'|g" {} \; 2>/dev/null

# 创建应用图标目录
echo "🎨 准备应用资源..."
cd mobile
mkdir -p res/icon/android res/splash/android

# 创建简单的应用图标（使用ImageMagick或创建占位符）
for size in "36:ldpi" "48:mdpi" "72:hdpi" "96:xhdpi" "144:xxhdpi" "192:xxxhdpi"; do
    IFS=':' read -r pixels density <<< "$size"
    icon_file="res/icon/android/icon-${pixels}-${density}.png"
    
    # 如果有convert命令（ImageMagick），创建图标
    if command -v convert >/dev/null 2>&1; then
        convert -size ${pixels}x${pixels} xc:"#1989fa" -fill white -gravity center \
                -pointsize $((pixels/4)) -annotate +0+0 "记" "$icon_file"
    else
        # 否则创建占位文件
        touch "$icon_file"
    fi
done

# 更新config.xml配置
echo "⚙️  更新Cordova配置..."
cat > config.xml << 'EOF'
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.accounting.app" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>记账本</name>
    <description>一个简单易用的记账本应用</description>
    <author email="dev@accounting.app" href="https://accounting.app">
        记账本团队
    </author>
    <content src="index.html" />
    
    <!-- 网络访问权限 -->
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    
    <platform name="android">
        <allow-intent href="market:*" />
        <access origin="*" />
        <allow-navigation href="*" />
        
        <!-- 应用图标 -->
        <icon density="ldpi" src="res/icon/android/icon-36-ldpi.png" />
        <icon density="mdpi" src="res/icon/android/icon-48-mdpi.png" />
        <icon density="hdpi" src="res/icon/android/icon-72-hdpi.png" />
        <icon density="xhdpi" src="res/icon/android/icon-96-xhdpi.png" />
        <icon density="xxhdpi" src="res/icon/android/icon-144-xxhdpi.png" />
        <icon density="xxxhdpi" src="res/icon/android/icon-192-xxxhdpi.png" />
        
        <!-- Android权限 -->
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    </platform>
    
    <!-- 应用偏好设置 -->
    <preference name="DisallowOverscroll" value="true" />
    <preference name="android-minSdkVersion" value="24" />
    <preference name="android-targetSdkVersion" value="34" />
    <preference name="StatusBarOverlaysWebView" value="false" />
    <preference name="StatusBarBackgroundColor" value="#1989fa" />
    <preference name="StatusBarStyle" value="lightcontent" />
    <preference name="Fullscreen" value="false" />
    
    <!-- 插件 -->
    <plugin name="cordova-plugin-whitelist" version="1" />
    <plugin name="cordova-plugin-statusbar" version="^4.0.0" />
</widget>
EOF

# 构建APK
echo "🏗️  构建Android APK..."

# 添加Android平台（如果还没有）
cordova platform add android >/dev/null 2>&1 || echo "Android平台已存在"

# 构建调试版本
echo "正在编译Android APK，这可能需要几分钟..."
cordova build android --debug --verbose

if [ $? -eq 0 ]; then
    echo ""
    echo "🎉 APK构建成功！"
    
    # 查找生成的APK文件
    APK_DEBUG=$(find platforms/android -name "*debug*.apk" -type f | head -1)
    
    if [ -n "$APK_DEBUG" ]; then
        # 复制APK到项目根目录
        cp "$APK_DEBUG" "$PROJECT_ROOT/记账本-debug.apk"
        APK_SIZE=$(du -h "$PROJECT_ROOT/记账本-debug.apk" | cut -f1)
        
        echo "📱 APK文件信息:"
        echo "   位置: $PROJECT_ROOT/记账本-debug.apk"
        echo "   大小: $APK_SIZE"
        echo ""
        echo "📲 安装说明:"
        echo "1. 将 记账本-debug.apk 传输到Android设备"
        echo "   - 通过USB传输"
        echo "   - 通过微信/QQ发送给自己"
        echo "   - 通过云盘下载"
        echo ""
        echo "2. 在Android设备上安装:"
        echo "   - 进入设置 → 安全 → 允许安装未知来源应用"
        echo "   - 找到APK文件，点击安装"
        echo ""
        echo "⚠️  重要提醒:"
        echo "   - 确保后端服务运行在: http://${LOCAL_IP}:3000"
        echo "   - 手机需要连接到同一WiFi网络"
        echo "   - 首次启动可能需要几秒钟加载"
        echo ""
        echo "🚀 启动后端服务命令:"
        echo "   cd $PROJECT_ROOT/backend && npm run dev"
        
        # 创建快速启动脚本
        cat > "$PROJECT_ROOT/start-for-mobile.sh" << EOL
#!/bin/bash
echo "🚀 启动记账本后端服务..."
echo "📱 手机APK将连接到: http://${LOCAL_IP}:3000"
echo ""
cd "$PROJECT_ROOT/backend"
npm run dev
EOL
        chmod +x "$PROJECT_ROOT/start-for-mobile.sh"
        echo "   或使用: $PROJECT_ROOT/start-for-mobile.sh"
        
    else
        echo "❌ 未找到生成的APK文件"
        echo "检查构建输出目录:"
        find platforms/android -name "*.apk" -type f 2>/dev/null || echo "没有找到APK文件"
    fi
else
    echo "❌ APK构建失败"
    echo ""
    echo "🔧 故障排除建议:"
    echo "1. 检查Java版本: java -version"
    echo "2. 检查Android SDK: ls -la $ANDROID_HOME/platforms/"
    echo "3. 检查构建工具: ls -la $ANDROID_HOME/build-tools/"
    echo "4. 重新运行: cordova requirements android"
    exit 1
fi